package control;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import business.BookingManager;
import model.BookingDTO;

/**
 * Servlet implementation class UpdateDeleteServlet
 */

public class UpdateBookingServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateBookingServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			processRequest(request,response);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			processRequest(request,response);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, ParseException {
		
			BookingManager bm = new BookingManager();
			BookingDTO book = new BookingDTO();
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			Date dStart = null;
			 try {
	                dStart = df.parse(request.getParameter("timestamp"));
	            } catch (ParseException e) {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
	            }
			 	int currentFacilityId = Integer.valueOf(request.getParameter("currentFacilityID"));
			 	int facilityID = Integer.valueOf(request.getParameter("facilityID"));
			 
			 	System.out.println("Current facility id: "+ currentFacilityId + " Selected: "+ facilityID);
			 	book.setFacilityID(facilityID<0?currentFacilityId:facilityID);
				book.setStartDate(dStart);
				book.setPeriod(Integer.parseInt(request.getParameter("period")));
				Calendar cal = Calendar.getInstance();
				cal.setTime(book.getStartDate());
				System.out.println(cal.getTimeInMillis());
				book.setEndDate(new Date(cal.getTimeInMillis() + book.getPeriod()
						* 86400000));
				book.setPriority(request.getParameter("priority"));
				book.setReason(request.getParameter("reason"));
				book.setBookingID(Integer.parseInt(request.getParameter("bookingID")));
				ArrayList<BookingDTO> bookings = bm.findBookingbyFacilityID(book.getFacilityID());
				boolean overlap = true;
				if (!bookings.isEmpty()) {
					Iterator<BookingDTO> i = bookings.iterator();
					while (i.hasNext()) {
						BookingDTO b = i.next();
						if (book.getStartDate().before(b.getStartDate())
								&& book.getEndDate().before(b.getStartDate())
								|| book.getStartDate().after(b.getEndDate())) {
							overlap=false;
							response.sendRedirect("NotAvailable.jsp?reason=BOOKING_DATE_OVERLAPPED");
							return;
						}}
						if (!overlap) {
							bm.updateBooking(book);
						}
				}else{
					bm.updateBooking(book);
				}
			 	
				RequestDispatcher rd = request.getRequestDispatcher("/SearchBook");
				try {
					rd.forward(request, response);
				} catch (ServletException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
}



